import os
import tempfile
import shutil
from typing import Dict, Any, List, Optional
import re
from datetime import datetime

from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import JSONResponse
import uvicorn

# 导入原有的分析模块
import sys
import importlib.util

# 动态导入中文文件名的模块
module_path = os.path.join(os.path.dirname(__file__), "工伤鉴定书分析.py")
spec = importlib.util.spec_from_file_location("injury_analysis", module_path)
injury_analysis = importlib.util.module_from_spec(spec)
spec.loader.exec_module(injury_analysis)

# 从模块中导入需要的类和函数
InjuryAssessmentAnalyzer = injury_analysis.InjuryAssessmentAnalyzer
classify_injury_assessment_type = injury_analysis.classify_injury_assessment_type
detect_official_seal_in_text = injury_analysis.detect_official_seal_in_text
detect_seal_in_image = injury_analysis.detect_seal_in_image

app = FastAPI(
    title="工伤鉴定书分析API",
    description="用于分析工伤鉴定书文件的API接口",
    version="1.0.0"
)

# API密钥配置
API_KEY = "sk-20856422ed6644e3827b9d5403c9542a"

# 支持的文件类型
SUPPORTED_EXTENSIONS = {
    '.pdf': 'application/pdf',
    '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.bmp': 'image/bmp',
    '.tiff': 'image/tiff',
    '.webp': 'image/webp'
}

def validate_file_type(filename: str) -> bool:
    """验证文件类型是否支持"""
    ext = os.path.splitext(filename.lower())[1]
    return ext in SUPPORTED_EXTENSIONS

def extract_institution_info(text: str) -> str:
    """从文本中提取鉴定机构信息"""
    institution_patterns = [
        r'([^\n]*省[^\n]*劳动能力鉴定委员会[^\n]*)',
        r'([^\n]*市[^\n]*劳动能力鉴定委员会[^\n]*)',
        r'([^\n]*司法鉴定所[^\n]*)',
        r'([^\n]*司法鉴定中心[^\n]*)',
        r'([^\n]*鉴定委员会[^\n]*)',
        r'([^\n]*鉴定机构[^\n]*)'
    ]
    
    for pattern in institution_patterns:
        match = re.search(pattern, text)
        if match:
            return match.group(1).strip()
    return ""

def extract_assessment_date(text: str) -> str:
    """从文本中提取鉴定日期"""
    date_patterns = [
        r'(\d{4}年\d{1,2}月\d{1,2}日)',
        r'(\d{4}-\d{1,2}-\d{1,2})',
        r'(\d{4}/\d{1,2}/\d{1,2})',
        r'鉴定日期[：:](\d{4}年\d{1,2}月\d{1,2}日)',
        r'出具日期[：:](\d{4}年\d{1,2}月\d{1,2}日)'
    ]
    
    for pattern in date_patterns:
        match = re.search(pattern, text)
        if match:
            return match.group(1).strip()
    return ""

def analyze_document_validity(text: str, assessment_type: str, has_seal: bool) -> tuple[str, str]:
    """分析文档有效性"""
    validity_issues = []
    
    # 检查基本要素
    if not extract_institution_info(text):
        validity_issues.append("缺少鉴定机构信息")
    
    if not extract_assessment_date(text):
        validity_issues.append("缺少鉴定日期")
    
    if not has_seal:
        validity_issues.append("未检测到官方印章")
    
    # 检查关键内容
    if "鉴定" not in text and "认定" not in text:
        validity_issues.append("缺少鉴定或认定相关内容")
    
    if assessment_type == "无法识别/可能为非标准工伤鉴定书":
        validity_issues.append("文档类型无法识别")
    
    # 生成有效性说明
    if not validity_issues:
        validity_desc = "文档格式规范，包含必要的鉴定要素，具备基本的法律效力要件。"
        can_be_evidence = "是"
    else:
        validity_desc = f"文档存在以下问题：{'; '.join(validity_issues)}。建议核实相关信息或补充必要材料。"
        can_be_evidence = "否" if len(validity_issues) > 2 else "需进一步核实"
    
    return validity_desc, can_be_evidence

def process_ai_analysis(analyzer: InjuryAssessmentAnalyzer, text: str, assessment_type: str, file_paths: List[str]) -> str:
    """处理AI分析结果，提取关键信息"""
    try:
        # 收集完整的AI分析结果
        full_analysis = []
        for chunk in analyzer.analyze_injury_assessment_stream(text, assessment_type, file_paths):
            full_analysis.append(chunk)
        
        analysis_text = "".join(full_analysis)
        
        # 提取关键信息并格式化
        key_sections = {
            "鉴定书类型确认": "",
            "鉴定机构和程序合规性": "",
            "鉴定内容专业性评估": "",
            "法律效力分析": "",
            "赔偿和待遇分析": "",
            "维权建议": "",
            "风险提示": ""
        }
        
        # 简化分析结果，提取核心内容
        lines = analysis_text.split('\n')
        current_section = ""
        
        for line in lines:
            line = line.strip()
            if any(section in line for section in key_sections.keys()):
                for section in key_sections.keys():
                    if section in line:
                        current_section = section
                        break
            elif current_section and line and not line.startswith('#'):
                if key_sections[current_section]:
                    key_sections[current_section] += " " + line
                else:
                    key_sections[current_section] = line
        
        # 构建简化的分析结果
        simplified_analysis = []
        for section, content in key_sections.items():
            if content:
                simplified_analysis.append(f"【{section}】{content[:200]}..." if len(content) > 200 else f"【{section}】{content}")
        
        return "\n\n".join(simplified_analysis) if simplified_analysis else analysis_text[:1000]
        
    except Exception as e:
        return f"AI分析过程中出现错误：{str(e)}"

@app.post("/analyze_injury_assessment")
async def analyze_injury_assessment(attendance_file: UploadFile = File(...)):
    """
    分析工伤鉴定书文件
    
    Args:
        attendance_file: 上传的工伤鉴定书文件（支持PDF、DOCX、图片格式）
    
    Returns:
        JSON格式的分析结果
    """
    
    # 验证文件类型
    if not validate_file_type(attendance_file.filename):
        raise HTTPException(
            status_code=400,
            detail=f"不支持的文件格式。支持的格式：{', '.join(SUPPORTED_EXTENSIONS.keys())}"
        )
    
    # 创建临时文件
    temp_dir = tempfile.mkdtemp()
    temp_file_path = None
    
    try:
        # 保存上传的文件到临时目录
        file_extension = os.path.splitext(attendance_file.filename.lower())[1]
        temp_file_path = os.path.join(temp_dir, f"temp_file{file_extension}")
        
        with open(temp_file_path, "wb") as buffer:
            shutil.copyfileobj(attendance_file.file, buffer)
        
        # 初始化分析器
        analyzer = InjuryAssessmentAnalyzer(API_KEY)
        
        # 提取文本内容
        try:
            text = analyzer.extract_text(temp_file_path)
        except Exception as e:
            raise HTTPException(status_code=400, detail=f"文件内容提取失败：{str(e)}")
        
        if not text.strip():
            raise HTTPException(status_code=400, detail="未能从文件中提取到有效文本内容")
        
        # 分析文档类型
        assessment_type = classify_injury_assessment_type(text)
        
        # 提取鉴定机构信息
        institution = extract_institution_info(text)
        
        # 提取鉴定日期
        assessment_date = extract_assessment_date(text)
        
        # 检测印章
        has_seal_text = detect_official_seal_in_text(text)
        has_seal_image = False
        if file_extension.lower() in ['.png', '.jpg', '.jpeg', '.bmp', '.tiff']:
            has_seal_image = detect_seal_in_image(temp_file_path)
        
        has_seal = has_seal_text or has_seal_image
        
        # 分析文档有效性
        validity_desc, can_be_evidence = analyze_document_validity(text, assessment_type, has_seal)
        
        # 进行AI分析（可选，用于增强分析结果）
        try:
            ai_analysis = process_ai_analysis(analyzer, text, assessment_type, [temp_file_path])
            # 将AI分析结果融入到文件内容中
            enhanced_content = f"原始文档内容摘要：{text[:500]}...\n\n专业分析：\n{ai_analysis}"
        except Exception as e:
            # 如果AI分析失败，使用原始文本
            enhanced_content = text[:1000] + "..." if len(text) > 1000 else text
        
        # 构建响应
        response_data = {
            "文件类型": assessment_type,
            "鉴定机构": institution,
            "鉴定日期": assessment_date,
            "文件内容": enhanced_content,
            "文件有效性说明": validity_desc,
            "是否可以作为证据": can_be_evidence
        }
        
        return JSONResponse(
            status_code=200,
            content=response_data
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"服务器内部错误：{str(e)}")
    
    finally:
        # 清理临时文件
        if temp_file_path and os.path.exists(temp_file_path):
            try:
                os.remove(temp_file_path)
            except:
                pass
        if os.path.exists(temp_dir):
            try:
                shutil.rmtree(temp_dir)
            except:
                pass

@app.get("/")
async def root():
    """API根路径"""
    return {
        "message": "工伤鉴定书分析API",
        "version": "1.0.0",
        "endpoints": {
            "POST /analyze_injury_assessment": "分析工伤鉴定书文件"
        }
    }

@app.get("/health")
async def health_check():
    """健康检查接口"""
    return {"status": "healthy", "timestamp": datetime.now().isoformat()}

if __name__ == "__main__":
    uvicorn.run(
        "injury_assessment_api:app",
        host="0.0.0.0",
        port=8004,
        reload=True
    )